package com.test.reggie.model.ip;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.text.TextUtils;

import com.lxj.xpopup.XPopup;
import com.test.reggie.base.BaseActivity;
import com.test.reggie.base.BasePresenter;
import com.test.reggie.bean.State;
import com.test.reggie.databinding.ActivityIPSettingBinding;
import com.test.reggie.http.API;
import com.yechaoa.yutils.ToastUtil;

/**
 * IP设置
 */
public class IPSettingActivity extends BaseActivity<ActivityIPSettingBinding, BasePresenter> {

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView() {
        if (API.kv.decodeString(State.ip) == null || TextUtils.isEmpty(API.kv.decodeString(State.ip))) {
            viewBinding.etIp.setText("http://");
        } else {
            viewBinding.etIp.setText(API.kv.decodeString(State.ip));
        }
    }

    @Override
    protected void initData() {
        viewBinding.btnSave.setOnClickListener(v -> {
            if (TextUtils.isEmpty(viewBinding.etIp.getText().toString().trim())) {
                ToastUtil.showCenter("IP不能为空");
            } else if (!viewBinding.etIp.getText().toString().trim().startsWith("http://") &&
                    !viewBinding.etIp.getText().toString().trim().startsWith("https://")) {
                ToastUtil.showCenter("请以http://或https://开头");
            } else if ("http://".equals(viewBinding.etIp.getText().toString().trim()) ||
                    "https://".equals(viewBinding.etIp.getText().toString().trim())) {
                ToastUtil.showCenter("请输入IP地址或域名");
            } else {
                new XPopup.Builder(this).asConfirm("提示",
                        "结束应用重新进入IP才会改变，确定退出应用重新进入吗",
                        () -> {
                            API.kv.encode(State.ip, viewBinding.etIp.getText().toString().trim());
                            setResult(Activity.RESULT_OK);
                            finish();
                        }).show();
            }
        });
    }
}